package com.vilen.L_5;

import java.io.*;

/**
 * Created by vilen on 2015/4/8.
 */
public class IOUtil {
    /**
     * 读取指定文件内容，按照16进制输出到控制台
     * 并且实现每输出10个byte 换行
     *单字节不适合大文件
     * @param fileName
     */
    public static void printHex(String fileName) throws IOException {
        FileInputStream in = new FileInputStream(fileName);
        int b;
        int i = 1;//换行用
        while ((b=in.read())!=-1){
            if(b<= 0xf){
                //单位数前面补0
                System.out.print("0");
            }
            System.out.print(Integer.toHexString(b) + "  ");//b转换成16进制字符串
            if(i++%10 == 0){
                System.out.println();
            }
        }
        in.close();
    }

    /**
     * 批量读取，对大文件而言效率高
     * @param filename
     * @throws Exception
     */
    public static void printHexByByteArray(String filename) throws Exception {
        FileInputStream in = new FileInputStream(filename);
        byte[] buf = new byte[8*1024];
        //从in中读取字节，放入buf 字节数组中，从0开始，最多buf.length
        //返回读到字节的个数，不确定
//        int bytes = in.read(buf,0,buf.length);
//        int j = 1;
//        for(int i =0;i<bytes;i++){
//            if (buf[i]<=0xf){
//                System.out.print("0");
//            }
//            System.out.print(Integer.toHexString(buf[i] & 0xff)+ " ");
//            if (j++%10==0){
//                System.out.println();
//            }
//        }
        int bytes = 0;
        int j = 1;
        while ((bytes = in.read(buf,0,buf.length))!=-1){
            for (int i =0;i<bytes;i++){
                System.out.print(Integer.toHexString(buf[i] & 0xff) + " ");
                //换行
                if (j++%10==0){
                    System.out.println();
                }
            }

        }
        in.close();
    }
    public static void copyFile(File srcFile,File destFile)throws IOException{
        if (!srcFile.exists()){
            throw new IllegalArgumentException("原文件"+srcFile+"不存在");
        }
        if(!srcFile.isFile()){
            throw new IllegalArgumentException(srcFile+"不是文件");
        }
        FileInputStream in = new FileInputStream(srcFile);
        FileOutputStream out = new FileOutputStream(destFile);
        byte[] buf = new byte[8*1024];
        int b;
        while ((b = in.read(buf,0,buf.length))!=-1){
            out.write(buf,0,b);
            out.flush();//最好加上
        }
        in.close();
        out.close();
    }

}
